package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    String prefix;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            // 1. 获取模板
            Template template = configuration.getTemplate("article.ftl");
            // 2. 准备数据
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            Integer userId = apAuthor.getUserId();
            Map dataModel = new HashMap();
            dataModel.put("authorApUserId",userId); // 作者对应的用户id
            dataModel.put("article",apArticle); // 文章基本信息
            dataModel.put("content", JSONArray.parseArray(content,Map.class)); // 文章基本信息
            // 3. 用数据替换模板，输出到指定的输出流中
            StringWriter writer = new StringWriter(); // 字符串输出流
            template.process(dataModel,writer);
            String contentHtml = writer.toString(); // 替换后的文本内容
            // 4. 将静态也 上传到minIO中    静态页名称:   articleId + .html
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", new ByteArrayInputStream(contentHtml.getBytes()));
            // 5. 将minio中静态页面的路径  设置到 article表的static_url属性上
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle) ; // 修改文章静态页路径
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败  当前文章信息: {} ",apArticle);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }


    }
}
